package com.wingstudio.springcloud.controller;

import com.wingstudio.springcloud.lib.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.wingstudio.springcloud.entities.Payment;
import com.wingstudio.springcloud.result.R;

import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

/**
 * @Author ITcz
 * @Data 2020-12-08 - 20:12
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
public class OrderController {
//    public static final String PAYMENT_URL = "http://127.0.0.1:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalance loadBalance;

    @GetMapping("/payment/create")
    public R create(Payment payment) {
        HashMap resultMap = new HashMap();
        resultMap.put("result", restTemplate.postForObject(PAYMENT_URL+"/payment/create", payment, R.class));
        return R.ok(resultMap);
    }

    @GetMapping("/payment/get/{id}")
    public R getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id, R.class);
    }

    @GetMapping("/payment/getForEntity/{id}")
    public R getPaayment2(@PathVariable("id") Long id){
        ResponseEntity<R> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, R.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
        log.info(entity.getHeaders()+"\t"+entity.getStatusCode()+"\t"+entity.getBody());
            return entity.getBody();
        }else {
            return R.error(444, "操作失败");
        }
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalance.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb", String.class );
    }


}
